package com.adhere.system.service.impl;

import com.adhere.system.mapper.RbacRoleMapper;
import com.adhere.system.mapper.RbacRolePrivilegeMapper;
import com.adhere.system.pojo.dto.RolePrivilegeDto;
import com.adhere.system.service.IRbacPrivilegeService;
import com.adhere.system.service.IRbacUserService;
import com.adhere.system.utils.CodeUtils;
import com.adhere.system.pojo.RbacPrivilege;
import com.adhere.system.pojo.RbacRole;
import com.adhere.system.pojo.RbacRolePrivilege;
import com.adhere.system.pojo.vo.PageVo;
import com.adhere.system.pojo.vo.RoleVo;
import com.adhere.system.service.IRbacRoleService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * <p>
 * 角色表删除执行：逻辑真删除 服务实现类
 * </p>
 *
 * @author 
 * @since 2021-04-02
 */
@Service
public class RbacRoleServiceImpl extends ServiceImpl<RbacRoleMapper, RbacRole> implements IRbacRoleService {

    @Autowired
    private RbacRoleMapper roleMapper;

    @Autowired
    private RbacRolePrivilegeMapper rolePrivilegeMapper;

    @Autowired
    private IRbacPrivilegeService privilegeService;

    @Autowired
    private IRbacUserService userService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public void addRole(RbacRole role, List<String> privilegeCodeList) {
        QueryWrapper<RbacRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", role.getName());
        RbacRole rbacRoleRepeat = roleMapper.selectOne(queryWrapper);
        if (rbacRoleRepeat != null) {
            throw new IllegalArgumentException("角色名称已经存在");
        }

        int result = roleMapper.insert(role);
        if (result == 1) {
            String roleCode = CodeUtils.encode(role.getId());
            role.setCode(roleCode);
            roleMapper.updateById(role);

            if (!ObjectUtils.isEmpty(privilegeCodeList)) {
                // 添加角色与权限的关联关系
                privilegeCodeList.forEach(privilegeCode -> {
                    RbacRolePrivilege rbacRolePrivilege = new RbacRolePrivilege().setRoleCode(roleCode).setPrivilegeCode(privilegeCode);
                    rolePrivilegeMapper.insert(rbacRolePrivilege);
                });
            }
        }
    }

    /**
     * 查询指定用户的权限列表
     * @param userCode
     * @return
     */
    @Override
    public List<RbacRole> getRoleListByUserCode(String userCode) {
        return roleMapper.getRoleListByUserCode(userCode);
    }

    /**
     * 更新指定角色的权限信息
     * @param rolePrivilegeDto
     */
    @Override
    public void updateRolePrivilege(RolePrivilegeDto rolePrivilegeDto) {
        String roleCode = rolePrivilegeDto.getRoleCode();
        List<String> privilegeCodeList = rolePrivilegeDto.getPrivilegeCodeList();
        // 先删除这个角色所有的权限信息
        QueryWrapper<RbacRolePrivilege> RPWrapper = new QueryWrapper<>();
        RPWrapper.eq("role_code", roleCode);
        rolePrivilegeMapper.delete(RPWrapper);
        if (!ObjectUtils.isEmpty(privilegeCodeList)) {
            // 添加传递过来的权限
            privilegeCodeList.stream().distinct().forEach(privilegeCode -> {
                RbacRolePrivilege rbacRolePrivilege = new RbacRolePrivilege().setRoleCode(roleCode).setPrivilegeCode(privilegeCode);
                rolePrivilegeMapper.insert(rbacRolePrivilege);
            });
        }

        // 根据角色code 查询用户code列表
        List<String> userCodeList = userService.getUserListByRoleCode(roleCode);
        userCodeList.forEach(userCode -> {
            // 根据用户code 查询权限列表
            List<RbacPrivilege> privilegeList = privilegeService.getPrivilegeListByUserCode(userCode);
            try {
                String privilegeListJson = objectMapper.writeValueAsString(privilegeList);
                redisTemplate.opsForValue().set(userCode, privilegeListJson);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
        });

    }


    /**
     * 根据角色名称分页查询权限列表
     * @param currentPage
     * @param pageSize
     * @param name
     * @return
     */
    @Override
    public PageVo<RbacRole> getRolePage(Integer currentPage, Integer pageSize, String name) {
        Page<RbacRole> page = new Page<>(currentPage, pageSize);
        QueryWrapper<RbacRole> wrapper = new QueryWrapper<>();
        if (StringUtils.hasText(name)) {
            wrapper.like("name", name);
        }
        wrapper.orderByDesc("create_time");
        Page<RbacRole> rolePage = roleMapper.selectPage(page, wrapper);
        return new PageVo<RbacRole>()
                .setObjectList(rolePage.getRecords())
                .setPageSize(pageSize)
                .setCurrentPage(currentPage)
                .setTotal(rolePage.getTotal());
    }

    @Override
    public RoleVo getRoleDetailByRoleCode(String roleCode) {
        return roleMapper.getRoleDetailByRoleCode(roleCode);
    }

}
